$(function() {
	var socketUrl = 'wss://yunliao.phpyun.com/wss';
	if ("WebSocket" in window) {
		webSocket(socketUrl,2);
		chatOnLoad();
	} else {
		console.log("您的浏览器不支持聊天!");
	}
	// 发送消息
	$('#send').click(function() {
		if(socket && socket.readyState == 1){
			send();
		}else{
			webSocket(socketUrl, 2);
			var timer = setInterval(function(){
				if(socket && socket.readyState == 1){
					clearInterval(timer);
					send();
				}
			},500);
			setTimeout(function(){
				if(timer){
					clearInterval(timer);
				}
			},10000);
		}
	});
	// 发送简历
	if ($('#sendExpcet')) {
		$('#sendExpcet').click(function() {
			sendExpcet();
		});
	}
	// 邀请面试
	if ($('#invite')) {
		$('#invite').click(function() {
			inviteCheck();
		});
	}// 发送职位
	if ($('#sendJob')) {
		$('#sendJob').click(function() {
			sendJob();
		});
	}
	// 发送职位
	if ($('#closeJob')) {
		$('#closeJob').click(function() {
			$('#joblist').addClass('none');
		});
	} 
	// 不感兴趣
	if ($('#nochat')) {
		$('#nochat').click(function() {
			nochat();
		});
	}
	if(typeof chat_single != 'undefined'){
		// 获取准备信息
		getPrepare();
	}
	if($('#lookresume')){
		$('#lookresume').click(function() {
			if(expect){
				window.location.href = expect.wapurl;
			}
		});
	}
	if($('#toCompany')){
		$('#toCompany').click(function() {
			if(company){
				window.location.href = company.wapurl;
			}
		});
	}
	timeFormat();
	//输入框失去焦点时，聊天内容高度，不大于屏幕高度，页面置顶,IOS需要处理此问题
	var u = navigator.userAgent;
	if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
		$('#send_content').on('blur',function(){
			var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
			var scrollHeight = document.getElementById('chat_content').scrollHeight;
			if(scrollHeight + 160 <clientHeight){
				window.scroll(0,0);
			}
		});
	}
});
function webSocket(socketUrl,islink){
	var ping_timer = null;
		socket = new WebSocket(socketUrl);
		socket.onopen = function() {
			islink = 1;
			//向聊天服务器发送心跳包
			var ping = {
				type: 'ping'
			};
			ping_timer = setInterval(function() {
				if (socket && socket.readyState == 1){
					socket.send(JSON.stringify(ping));
				}else{
					socket.close();
				}
			}, 25000);
		};
		socket.onerror = function() {
			islink = 2;
			if(ping_timer){
				clearInterval(ping_timer);
			}
			/*
			layer.open({
				content: chat_name+'服务器无法连接',
				skin: 'msg',
				time: 2
			});
			*/
		};

		socket.onclose = function() {
			if(ping_timer){
				clearInterval(ping_timer);
			}
			islink = window.localStorage.getItem("islink");
			if(islink == 1){
				webSocket(socketUrl,2);
				chatOnShow();
			}
		};
		//捕捉socket端发来的事件
		socket.onmessage = function(event) {
			var e = JSON.parse(event.data);
			switch (e.type) {
				//显示收到的消息
				case 'getMessage':
					getMessage(e.data);
					break;
				case 'error':
					islink = 2;
					break;
			}
		};
}
// 加载聊天数据
function chatOnLoad(){
	$.post(wapurl + "index.php?c=chat&a=goChat", {
		rand: Math.random()
	}, function(data) {
		if (data) {
			var res = JSON.parse(data);
			mine = res.mine;
			var t = setInterval(function(){
				if (socket && socket.readyState == 1){
					clearInterval(t);
					if(res.yuntoken && res.yuntoken.token){
						var yuntoken = res.yuntoken.token;
						var bind = {
							type: 'bind',
							data: {
								uid: mine.id,
								usertype: mine.usertype,
								yuntoken: yuntoken
							}
						}
						socket.send(JSON.stringify(bind));
						window.localStorage.setItem("islink", "1");
					}else{
						window.localStorage.setItem("islink", "2");
					}
				}
			},100);
			setTimeout(function(){
				if(t){
					clearInterval(t);
				}
			},10000);

			if(typeof chat_single != 'undefined'){
				if (socket && socket.readyState == 1){
					setTimeout(function(){
						if(inviteid !=''){
							sendInvite(inviteid);
						}
					},800);
				}
			}
		}
	});
}
// 重新连接请求数据
function chatOnShow(){
	$.post(wapurl + "index.php?c=chat&a=getToken", {
		rand: Math.random()
	}, function(data) {
		if (data) {
			var res = JSON.parse(data);
			var t = setInterval(function(){
				if (socket && socket.readyState == 1){
					clearInterval(t);
					if(res.yuntoken){
						var bind = {
							type: 'bind',
							data: {
								uid: mine.id,
								usertype: mine.usertype,
								yuntoken: res.yuntoken
							}
						}
						socket.send(JSON.stringify(bind));
						window.localStorage.setItem("islink", "1");
					}else{
						window.localStorage.setItem("islink", "2");
					}
				}
			},500);
			setTimeout(function(){
				if(t){
					clearInterval(t);
				}
			},10000);
		}
	});
}
function back(){
	history.back();
}
function getPrepare(){
	$.post(wapurl + "index.php?c=chat&a=prepare", {
		'toid': toid,
		'totype': totype
	}, function(data) {
		if (data) {	
			var res = JSON.parse(data);
			var html = '',list = [];
			if(res.joblist){
				joblist = res.joblist;
				for(var i in joblist){
					list.push(i);
					html += '<div class="chatjob_list">';
					html +=	'<div class="chatjob_name">' + joblist[i].name + '</div>';
					html += '<div class="chatjob_xz">' + joblist[i].job_salary + '</div>';
					html += '<div class="chatjob_info">' + joblist[i].job_city_one + '-' + joblist[i].job_city_two;
					if(joblist[i].job_edu){
						html += '<span class="chatjob_info_line">|</span>' + joblist[i].job_edu+'学历';
					}
					if(joblist[i].job_exp){
						html += '<span class="chatjob_info_line">|</span>' + joblist[i].job_exp+'经验';
					}
					html += '</div>';
					html += '<span class="chatjob_bth" data-jobid="'+ joblist[i].id +'" onclick="jobShow(this)">发送</span></div>';
				}
				$('#chatjob_list').html(html);
			}else{
				html = '<div class="chat_nojob">~ 亲 , 暂无招聘中职位哦！</div>';
				$('#chatjob_list').html(html);
			}
			if(res.expect){
				expect = res.expect;
			}
			if(res.company){
				company = res.company;
			}
			// 渲染聊天记录
			moreChat();
		}
	});
}

// 发送消息
function send() {
	var content = document.getElementById('send_content');
	if (content.value != '') {
		// 发送聊天
		if(toid != ''){
			sendMessage(content.value,'char','');
			content.value = '';
			checkSend();
		}else{
			layer.open({
				content: '请选择'+chat_name+'对象',
				skin: 'msg',
				time: 2
			});
		}
	}
}
function getMessage(msg){
	if (msg.id && msg.totype == mine.usertype) {
		if(typeof toid != 'undefined' && msg.id == toid){
			var html = render(msg, 'get');
			// 收到消息处理
			setTimeout(function(){
				$.post(wapurl + "index.php?c=chat&a=setMsgStatus", {
					'id': toid,
					'type': totype,
					'nowid': mine.id,
					'nowtype': mine.usertype
				}, function(data) {
					if(data){
						var res = eval('(' + data + ')');
						if(res.errmsg){
							layermsg(res.errmsg, 2, function(){
								location.href = wapurl;
							});
						}
					}
				});
			},500);
		}else{
			var content = (msg.content||'').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
				.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
				.replace(/img\[([^\s]+?)\]/g, function(img){  //转义图片
				  return '[图片]';
				});
			// 聊天列表处理接收信息
			if ($('#chatList').length > 0){
				if ($('#chat_' + msg.id).length > 0){
					var msg_new = $('#chat_' + msg.id).find('.chat_msg_new');
					if(msg_new.text() == ''){
						$('#chat_' + msg.id).find('.chat_msg_new').text(1);
						$('#chat_' + msg.id).find('.chat_new_p').text(content);
						$('#chat_' + msg.id).find('.chat_new_time').text(timeFormat(msg.timestamp));
					}else if(parseInt(msg_new.text()) > 0){
						var num = parseInt(msg_new.text()) + 1;
						$('#chat_' + msg.id).find('.chat_msg_new').text(num);
						$('#chat_' + msg.id).find('.chat_new_p').text(content);
						$('#chat_' + msg.id).find('.chat_new_time').text(timeFormat(msg.timestamp));
					}
				} else {
					
					var html = '';
					html += '<li id="chat_'+msg.id+'" onclick="toChat('+msg.id+','+msg.ftype+','+msg.ftype+')">';
					html += '<div class="chat_msg_tx"><img src="'+msg.avatar+'" width="50" height="50"></div><span class="chat_msg_new">1</span>';
					html += '<div class="chat_name_box"><div class="chat_name"><span class="chat_hrname">'+msg.linkman+'</span>&nbsp;&nbsp;&nbsp;';
					if (msg.ftype=='1'){
						var content = msg.content;
						if(msg.msgtype == 'char'){
							if(content.indexOf('[img')){
								content = '图片消息';
							}
						}else{
							if(msg.msgtype == 'job'){
								content = '职位消息';
							}else if(msg.msgtype == 'resume'){
								content = '简历消息';
							}else if(msg.msgtype == 'change'){
								content = '面试消息';
							}
						}
						html += content;
					}else{
						html += '<span class="chat_comname">'+msg.username+'</span>';
					}
					html += '</div>';
					html += '<div class="chat_new_p">'+content+'</div><span class="chat_new_time">'+msg.timefromat+'</span></li>';			
					$('#chatList').prepend(html);
				}
			}
			// foot
			if ($('#tzmsgNum').length > 0){
				var msg_new = $('#tzmsgNum');
				if(msg_new.text() == ''){
					msg_new.text(1);
					msg_new.show();
				}else if(parseInt(msg_new.text()) > 0){
					msg_new.text(parseInt(msg_new.text()) + 1);
					msg_new.show();
				}
			}
			// sysnews
			if ($('#syschatdiv').length > 0){
				$('#chatContent').text(msg.username);
				$('#chatTime').text(msg.timefromat);
				var msg_new = $('#chatUnread');
				if(msg_new.text() == '0'){
					msg_new.text(1);
				}else if(parseInt(msg_new.text()) > 0){
					msg_new.text(parseInt(msg_new.text()) + 1);
				}
				$('#syschat').removeClass('none');
				$('#sysnochat').addClass('none');
			}
		}
	}
}
// 加号和发送切换
function checkSend() {
	var content = document.getElementById('send_content').value;
	if (content.trim() != '') {
		$('#send').removeClass('none');
		$('#more').addClass('none');
	} else {
		$('#send').addClass('none');
		$('#more').removeClass('none');
	}
}
// 由简历/职位详情页进入,发预定消息
function prepare() {
	var pdata = {};
	if (jid != '' && joblist && joblist[jid] && jobShowed){
		var html = '<li class="chat_li"><div class="chat_yx_job" data-wapurl="' + joblist[jid].wapurl + '" onclick="toShow(this)">';
		html += '<span><div class="chat_yx_job_name">' + joblist[jid].name + '</div>';
		html += '<span class="chat_yx_xz">' + joblist[jid].job_salary + '</span>';
		html += '<div class="chat_yx_com_name">' + joblist[jid].com_name + '</div>';
		html += '<div class="">' + joblist[jid].job_city_one + '-' + joblist[jid].job_city_two;
		if(joblist[jid].job_exp){
			html += ' . ' + joblist[jid].job_exp+'经验';
		}
		if(joblist[jid].job_edu){
			html += ' . ' + joblist[jid].job_edu+'学历';
		}
		html += '</div>';
		html += '<div class="chat_yx_time">' + timeFormat() + ' 由你发起的沟通</div></span></div></li>';
		// 发送消息
		sendMessage(html,'job',jid);
		
		setTimeout(function(){
			var send = '你好，可以聊聊吗？这个职位我很感兴趣，希望进一步了解';
			sendMessage(send,'char','');
		},500);
	}
}

function sendExpcet() {
	if(expect){
		var html = '<li class="chat_li"><div class="chat_userresume" data-wapurl="' + expect.wapurl + '" onclick="toShow(this)">';
			html += '<span><div class="chat_userresume_name">' + expect.uname + ' <span class="chat_userresume_ys">' + expect.sex_n +',' + expect.age + '岁</span></div>';
			html += '<div class="chat_userresume_info">' + expect.exp_n + ' . ' + expect.edu_n + ' </div>';
			html += '<div class="chat_userresume_want">期望职位 <span class="chat_userresume_wantjob">' + expect.name +'</span> </div>';
			html += '<div class="chat_userresume_pic"><img src=" ' + expect.photo + ' "></div></span></div></li>';
			// 发送消息内容
			sendMessage(html,'resume',expect.id);
	}else{
		layer.open({
			content: '您还没有可以投递的简历',
			btn: ['前往发布', '取消'],
			yes: function(index) {
				location.href = wapurl + '/member/index.php?c=resume';
				layer.close(index);
			}
		});
	}
}

function toShow(obj){
	var url = obj.getAttribute('data-wapurl');
	if(url && url != ''){
		location.href = url;
	}
}

function inviteCheck() {
	var index = layer_load('执行中，请稍候...');
	//判断是否达到每天最大操作次数
	$.post(wapurl + '/index.php?c=ajax&a=ajax_day_action_check', {
			'type': 'interview'
		},
		function(data) {
			layer.closeAll('loading');
			data = eval('(' + data + ')');
			if (data.status == -1) {
				layermsg(data.msg);
				return false;
			} else if (data.status == 1) {

				$.post(wapurl + "/index.php?c=ajax&a=indexajaxresume", {
					show_job: 1
				}, function(data) {
					var data = eval('(' + data + ')');
					var status = data.status;
					if(status == 1){
							
						layer.open({
							title : [ '温馨提示', 'background-color: #FF4351; color:#fff;' ],
							content : data.msgList.join(''),
							anim  : 'up',
							btn   : '我知道了',
							shadeClose : false
						});
					}else if(status == 2){
						
						if(data.spid){
							
							layer.open({
								title : [ '温馨提示', 'background-color: #FF4351; color:#fff;' ],
								content : '当前账户套餐余量不足，请联系主账户增配！',
								btn : [ '确认', '取消' ],
								shadeClose : false
							});
						}else{
							 
							layer.open({
								content : data.msg,
								btn : [ '确认', '取消' ],
								shadeClose : false,
								yes : function() {
									window.location.href = wapurl + "/member/index.php?c=server&server=invite&id="+ toid;
								}
							});
						}
					}else if(status == 3){
						var inviteUrl  =  wapurl + 'index.php?c=resume&a=invite&uid='+toid +'&chat='+toid;
						if(jid!=''){
							inviteUrl += '&jobid='+jid;
							location.href = inviteUrl;
						}else{
							location.href = inviteUrl;
						}
					}else{
						if(data.login == 1){
								
							pleaselogin('您还未登录企业账号，是否登录？',wapurl+'/index.php?c=login')
						}else if(data.login == 2){
							layer.msg('请先申请企业用户',2,8);
						}else{
							layer.open({
								content:data.msg
								,btn:'我知道了'
							});

							return false;
						}
					}
				});
			}
		}
	);
}

function sendInvite(id){
	var html = '<li class="chat_li"><div class="chat_sendcont" data-inviteid="' + inviteid + '" onclick="inviteShow(this)">';
	html += '<div class="chat_sendcont_pic"><img src="' + mine.avatar + '"></div>';
	html += '<span class="chat_sendcont_p"><em class="chat_sendcont_yqbox">发送了面试邀请<i class="chat_sendcont_yq"></i></em></span></div></li>';
	// 发送消息
	sendMessage(html,'invite',id);
}
// 展示邀请详情
function inviteShow(obj){
	var id = obj.getAttribute('data-inviteid');
	if(id && id != ''){
		if(mine.usertype == 1){
			var url = wapurl + 'member/index.php?c=invitecont&id=' + id;
		}else{
			var url = wapurl + 'member/index.php?c=invite&chat=1';
		}
		location.href = url;
	}
}

function sendJob() {
	$('#joblist').removeClass('none');
}

function jobShow(obj) {
	var id = obj.getAttribute('data-jobid');
	$('#joblist').addClass('none');
	if(jid != id && jid > 0){
		if (mine.usertype == 1) {
			var change = '您更换了与招聘者沟通的职位';
		} else {
			var change = '您更换了与求职者沟通的职位';
		}
		// 发送消息
		sendMessage(change,'change','');
	}
	
	var jobhtml = '<li class="chat_li"><div class="chat_yx_job" data-wapurl="' + joblist[id].wapurl + '" onclick="toShow(this)">';
	jobhtml += '<span><div class="chat_yx_job_name">' + joblist[id].name + '</div>';
	jobhtml += '<span class="chat_yx_xz">' + joblist[id].job_salary + '</span>';
	jobhtml += '<div class="chat_yx_com_name">' + joblist[id].com_name + '</div>';
	jobhtml += '<div class="">' + joblist[id].job_city_one + '-' + joblist[id].job_city_two;
	if(joblist[id].job_exp){
		jobhtml += ' . ' + joblist[id].job_exp+'经验';
	}
	if(joblist[id].job_edu){
		jobhtml += ' . ' + joblist[id].job_edu+'学历';
	}
	jobhtml += '</div>';
	if(jid != id  && jid > 0){
		jobhtml += '<div class="chat_yx_time">' + timeFormat() + ' 由你发起的沟通</div></span></div></li>';
	}
	// 发送消息
	sendMessage(jobhtml,'job',id);
	// 设置当前沟通职位
	jid = id;
}

function nochat() {
	layer.open({
		content: '设定不感兴趣将会删除与TA的'+chat_name+'记录，并将TA加入'+chat_name+'黑名单，确定继续？'
		,btn: ['确定', '取消']
		,yes: function(index){
			layer.close(index);
			var loading = layer.open({type: 2});
			$.post(wapurl+"/index.php?c=chat&a=delChatLog", {to:toid, type: totype}, function (data) {
				layer.close(loading);
				if(data){
					var res = eval('(' + data + ')');
					if(res.errmsg){
						layermsg(res.errmsg,2,function(){
							location.href = wapurl;
						});
					}else{
						back();
					}
				}
			});
		}
	});
}
// 发送消息
function sendMessage(content, type, id){
	if(socket && socket.readyState == 1){
		// 根据消息类型区分保存内容
		if(type == 'job'){
			var msgcontent = 'jobid=' + id;
		}else if(type == 'resume'){
			var msgcontent = 'eid=' + id;
		}else if(type == 'invite'){
			var msgcontent = 'inviteid=' + id;
		}else{
			var msgcontent = content;
		}
		var mineData = {
			id: mine.id,
			ftype: mine.usertype,
			avatar: mine.avatar,
			username: mine.username,
			timestamp: new Date().getTime(),
			content: msgcontent,
			msgtype: type
		};
		var sendData = {
			mine: mineData,
			to: {
				id: toid,
				utype: totype
			}
		}
		var message = {
			type: 'chatMessage',
			data: {
				content: sendData
			}
		}
		// 保存聊天记录
		if(type != 'change'){
			var pdata = {
				to: sendData.to.id,
				totype: sendData.to.utype,
				content: msgcontent,
				timestamp: sendData.mine.timestamp,
				msgtype: sendData.mine.msgtype,
				nowid: sendData.mine.id,
				nowtype: sendData.mine.ftype
			};
			$.post(wapurl+"/index.php?c=chat&a=chatLog", pdata, function (data) {
				if(data){
					var res = eval('(' + data + ')');
					if(res.error != 0){
						if(res.error == 3){
							return layermsg(res.errmsg,2);
						}else if(res.errmsg){
							layermsg(res.errmsg,2,function(){
								location.href = wapurl;
							});
						}
					}else{
						socket.send(JSON.stringify(message));
					}
				}
			});
		}else{
			socket.send(JSON.stringify(message));
		}
		// 消息时间间隔超60秒，显示新时间
		if(sendData.mine.timestamp - sendTime > 60*1000){
			$("#chat_content").find('ul').append('<li class="chat_li"><div class="chat_sendtime">' + timeFormat(sendData.mine.timestamp) + '</div></li>');
			sendTime = sendData.mine.timestamp;
		}
		// 渲染消息内容
		mineData.htmlcontent = content;
		var html = render(mineData, 'send');
	}else{
		layer.open({
			content: chat_name+'功能加载中',
			skin: 'msg',
			time: 2
		});
	}
}
// 渲染消息内容
function render(msg, type){
	if(type == 'send'){
		// 发送
		if(msg.msgtype == 'char'){
			var content = rexContent(msg.htmlcontent);
			// 我说
			var html  = '<li class="chat_li"><div class="chat_sendcont">';
				html += '<div class="chat_sendcont_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p">' + content + '</span></div></li>';
		}else if(msg.msgtype == 'change'){
			var html = '<li class="chat_li"><div class="chat_comjobtip"><span class="chat_comjobtip_p">' + msg.htmlcontent + '</span></div></li>';
		}else{
			var html = msg.htmlcontent;
		}
	}else {
		// 接收
		if(msg.msgtype == 'char'){
			msg.content = rexContent(msg.content);
			// 他说
			var html = '<li class="chat_li"><div class="chat_other_say">';
				html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p2">' + msg.content + '</span></div></li>';
		}else{
			if(msg.msgtype == 'job'){
				if(msg.content.indexOf('jobid') != -1){
					var jobid = msg.content.replace('jobid=','');
					var html = getJobHtml(jobid);
				}
			}else if(msg.msgtype == 'resume'){
				if(msg.content.indexOf('eid') != -1){
					var eid = msg.content.replace('eid=','');
					var html = getResumeHtml(eid);
				}
			}else if(msg.msgtype == 'change'){
				if (msg.ftype == 1) {
					var change = '求职者更换了与您沟通的职位';
				} else {
					var change = '招聘者更换了与您沟通的职位';
				}
				var html = '<li class="chat_li"><div class="chat_comjobtip"><span class="chat_comjobtip_p">' + change + '</span></div></li>';
			}else if(msg.msgtype == 'invite'){
				if(msg.content.indexOf('inviteid') != -1){
					var inviteid = msg.content.replace('inviteid=','');
					var html = '<li class="chat_li"><div class="chat_other_say" data-inviteid="' + inviteid + '" onclick="inviteShow(this)">';
					html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
					html += '<span class="chat_sendcont_p2"><em class="chat_sendcont_jsbox">发送了面试邀请<i class="chat_sendcont_jsyq"></i></em></span></div></li>';
				}
			}else{
				var html = msg.content;
			}
		}
		// 消息时间间隔超60秒，显示新时间
		if(msg.timestamp - sendTime > 60*1000){
			$("#chat_content").find('ul').append('<div class="chat_sendtime">' + timeFormat(msg.timestamp) + '</div>');
			sendTime = msg.timestamp;
		}
	}
	$("#chat_content").find('ul').append(html);
	var scroll = document.getElementById('chat_content').scrollHeight;
	scrollTo(scroll);
	// 图片类型加载较慢，滚动到底部需要时间
	if($("#chat_content").find('ul').last().find('img')){
		// 上面滚动过之后，新的高度
		lastscroll = document.getElementById('chat_content').scrollHeight;
		var timer_num = 0;
		var timer = setInterval(function() {
			timer_num++;
			var imgscroll = document.getElementById('chat_content').scrollHeight;
			if(imgscroll > lastscroll || timer_num > 5){
				scrollTo(imgscroll);
				clearInterval(timer);
			}
		}, 200);
	}
	return html;
}
function getJobHtml(jobid, msg){
	var html = '';
	if(joblist && joblist[jobid]){
		html = '<li class="chat_li"><div class="chat_yx_job" data-wapurl="' + joblist[jobid].wapurl + '" onclick="toShow(this)">';
		html += '<span><div class="chat_yx_job_name">' + joblist[jobid].name + '</div>';
		html += '<span class="chat_yx_xz">' + joblist[jobid].job_salary + '</span>';
		html += '<div class="chat_yx_com_name">' + joblist[jobid].com_name + '</div>';
		html += '<div class="">' + joblist[jobid].job_city_one + '-' + joblist[jobid].job_city_two;
		if(joblist[jobid].job_exp){
			html += ' . ' + joblist[jobid].job_exp+'经验';
		}
		if(joblist[jobid].job_edu){
			html += ' . ' + joblist[jobid].job_edu+'学历';
		}
		html += '</div>';
		if(msg && msg.newjob){
			var msgtime = parseInt(msg.msgtime);
			var gtuser;
			if(msg.newjob == 1){
				gtuser = '你';
			}else{
				if(msg.fusertype == 1){
					if(mine.usertype == 1){
						gtuser = '你';
					}else{
						gtuser = '招聘者';
					}
				}else{
					if(mine.usertype == 1){
						gtuser = '求职者';
					}else{
						gtuser = '你';
					}
				}
			}
			html += '<div class="chat_yx_time">' + timeFormat(msgtime) + ' 由' + gtuser + '发起的沟通</div>';
		}
		html += '</span></div></li>';
	}
	return html;
}
function getResumeHtml(eid){
	var html = '';
	if(expect){
		html = '<li class="chat_li"><div class="chat_userresume" data-wapurl="' + expect.wapurl + '" onclick="toShow(this)">';
		html += '<span><div class="chat_userresume_name">' + expect.uname + ' <span class="chat_userresume_ys">' + expect.sex_n + ',' + expect.age + '岁</span></div>';
		html += '<div class="chat_userresume_info">' + expect.exp_n + ' . ' + expect.edu_n + ' </div>';
		html += '<div class="chat_userresume_want">期望职位 <span class="chat_userresume_wantjob">' + expect.name +'</span> </div>';
		html += '<div class="chat_userresume_pic"><img src=" ' + expect.photo + ' "></div></span></div></li>';
	}
	return html;
}
// 转义内容
function rexContent(content){
	content = (content||'').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
	.replace(/img\[([^\s]+?)\]/g, function(img){  //转义图片
      return '<img class="chat_photos" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
    })
	return content;
}
function upImage(obj){
	$('#imgform').submit();
	var iframe = $('#chat_iframe'), timer = setInterval(function() {
		var res;
		try {
			res = iframe.contents().find('body').text();
		} catch(e) {
			clearInterval(timer);
		}
		if(res){
			clearInterval(timer);
			iframe.contents().find('body').html('');
			try {
				res = JSON.parse(res);
			} catch(e){
				res = {};
			}
			if (res.msg){
				layermsg(res.msg);
			}else{
				focusInsert(document.getElementById("send_content"), 'img['+ (res.data.url||'') +']', true);
				send();
			}
		}
    }, 30);
    obj.value = '';
}

function timeFormat(nowtime) {
	if(nowtime){
		nowtime = new Date(nowtime);
	}else{
		nowtime = new Date();
	}
	var month = nowtime.getMonth(),
		day = nowtime.getDate(),
		hour = nowtime.getHours(),
		minutes = nowtime.getMinutes();
	month = month + 1;
	if (month < 10) {
		month = '0' + month;
	}
	if (hour < 10 && hour > 0) {
		hour = '0' + hour;
	}
	if (minutes < 10 && minutes > 0) {
		minutes = '0' + minutes;
	}
	if (day < 10 && day > 0) {
		day = '0' + day;
	}
	var time = month + '-' + day + ' ' + hour + ':' + minutes;
	return time;
}
// 页面滚动
function scrollTo(ypos) {
	var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
	if((ypos + 160) > clientHeight){
		// 兼容各种浏览器
		document.body.scrollTop = ypos;
		document.documentElement.scrollTop = ypos;
	}
}
//在焦点处插入内容
function focusInsert(obj, str, nofocus){
    var result, val = obj.value;
    nofocus || obj.focus();
    if(document.selection){ //ie
		result = document.selection.createRange(); 
		document.selection.empty(); 
		result.text = str; 
    } else {
		result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
		nofocus || obj.focus();
		obj.value = result.join('');
    }
}
//查看更多记录
function chatListMore(){
    var chatMain = $('#chat_content');
    var ul = chatMain.find('ul'), li = ul.children('.chat_li'); 
    
    if(li.length >= MAX_ITEM){
      var first = li.eq(0);
      first.prev().remove();
      if(!ul.prev().hasClass('chat_more')){
        ul.before('<li id="chat_more" class="chat_more" onclick="moreChat()"><div class="chat_comjobtip"><span class="chat_comjobtip_p">查看更多记录</span></div></li>');
      }
      first.remove();
    }
    chatMain.scrollTop(chatMain[0].scrollHeight + 1000);
}
function moreChat(){
	$.ajax({
		type : "post",
		url : wapurl + "index.php?c=chat&a=getChatPage",
		async: false,
		data : {'id': toid,'totype': totype,'page': page},
		dataType : "json",
		success : function(res) {
			if (res) {
				//准备数据
				var pint = setInterval(function(){
						if(mine.id){
							clearInterval(pint);
							prepare();
						}
					},100);
				page = page + 1;
				var scroll = null;
				if(page > 2){
					// 第二页开始，记录前一次滚动距离
					scroll = document.getElementById('chat_content').scrollHeight;
				}
				
				$('#chat_more').remove();
				if(res.code == 0){
					var chatlog = res.data;
					if(chatlog.length > 0){
						var mt = setInterval(function(){
							if(mine){
								clearInterval(mt);
								pastSend = chatlog[0].sendTime;
								for(var i in chatlog){
									renderPast(chatlog[i]);
									// 最后一条时，如还有历史消息，增加更多消息
									if(i == chatlog.length -1 && res.ismore){
										$("#chat_content").find('ul').prepend('<li id="chat_more" class="chat_more" onclick="moreChat()"><div class="chat_comjobtip"><span class="chat_comjobtip_p">查看更多记录</span></div></li>');
									}
									if(scroll){
										// 渲染后，滚动到上一页的距离
										var newScroll = document.getElementById('chat_content').scrollHeight;
										scrollTo(newScroll - scroll);
									}
								}
							}
						},50);
					}
				}
			}
		}
    });
}
//对方未在线，发送提醒
function unSend(msg){
	$.post(wapurl + "index.php?c=chat&a=unSend", {
		'nowtype': msg.ftype,
		'toid': msg.toid,
		'totype': msg.totype
	}, function() {});
}
// 渲染历史消息
function renderPast(msg){
	// 接收
	if(msg.msgtype == 'char'){
		msg.content = rexContent(msg.content);
		if(msg.mine){
			// 我说
			var html  = '<li class="chat_li"><div class="chat_sendcont">';
				html += '<div class="chat_sendcont_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p">' + msg.content + '</span></div></li>';
		}else{
			// 他说
			var html = '<li class="chat_li"><div class="chat_other_say">';
				html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p2">' + msg.content + '</span></div></li>';
		}
	}else{
		if(msg.msgtype == 'job'){
			if(msg.content.indexOf('jobid') != -1){
				var jobid = msg.content.replace('jobid=','');
				var html = getJobHtml(jobid, msg);
				jid = jobid;
				jobShowed = false;
			}
		}else if(msg.msgtype == 'resume'){
			if(msg.content.indexOf('eid') != -1){
				var eid = msg.content.replace('eid=','');
				var html = getResumeHtml(eid);
			}
		}else if(msg.msgtype == 'change'){
			if (mine.usertype == 1) {
				var change = '求职者更换了与您沟通的职位';
			} else {
				var change = '招聘者更换了与您沟通的职位';
			}
			var html = '<li class="chat_li"><div class="chat_comjobtip"><span class="chat_comjobtip_p">' + change + '</span></div></li>';
		}else if(msg.msgtype == 'invite'){
			if(msg.content.indexOf('inviteid') != -1){
				var qyid = msg.content.replace('inviteid=','');
				if(msg.mine){
					var html = '<li class="chat_li"><div class="chat_sendcont" data-inviteid="' + qyid + '" onclick="inviteShow(this)">';
					html += '<div class="chat_sendcont_pic"><img src="' + mine.avatar + '"></div>';
					html += '<span class="chat_sendcont_p"><em class="chat_sendcont_yqbox">发送了面试邀请<i class="chat_sendcont_yq"></i></em></span></div></li>';
				}else{
					var html = '<li class="chat_li"><div class="chat_other_say" data-inviteid="' + qyid + '" onclick="inviteShow(this)">';
					html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
					html += '<span class="chat_sendcont_p2"><em class="chat_sendcont_jsbox">发送了面试邀请<i class="chat_sendcont_jsyq"></i></em></span></div></li>';
				}
				if(inviteid !='' && inviteid == qyid){
					inviteid = '';
				}
			}
		}else{
			var html = msg.content;
		}
	}
	$("#chat_content").find('ul').prepend(html);
	// 消息时间间隔超60秒，显示新时间
	if(pastSend - msg.sendTime > 60*1000){
		$("#chat_content").find('ul').prepend('<li class="chat_li"><div class="chat_sendtime">' + timeFormat(parseInt(msg.sendTime)) + '</div></li>');
		pastSend = msg.sendTime;
	}
	if(page == 2){
		var scroll = document.getElementById('chat_content').scrollHeight;
		scrollTo(scroll);
		// 图片类型加载较慢，滚动到底部需要时间
		var timer_num = 0;
		var timer = setInterval(function() {
			timer_num++;
			var imgscroll = document.getElementById('chat_content').scrollHeight;
			scrollTo(imgscroll);
			if(timer_num > 20){
				clearInterval(timer);
			}
		}, 50);
	}
}